﻿using System;
using System.IO;
using System.Net;
using LaoLuo.IO;

namespace LaoLuo.Net
{
    /// <summary>
    /// 
    /// </summary>
    public static class WebRequestHelper
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="url"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static bool FileExists(string url, int timeout = 1000)
        {
            try
            {
                var request = (HttpWebRequest)WebRequest.Create(url);
                request.Timeout = timeout;
                request.Method = "HEAD";
                request.AllowAutoRedirect = false;
                return ((HttpWebResponse)request.GetResponse()).StatusCode == HttpStatusCode.OK;
            }
            catch (WebException)
            {
                return false;
            }
        }

        /// <summary>
        /// download a file from specified <see cref="url"/>, save it to specified <see cref="filename"/>, return a <see cref="FileInfo"/>
        /// </summary>
        /// <param name="url"></param>
        /// <param name="filename"></param>
        /// <param name="timeout"> </param>
        /// <param name="skipDownloadIfExists"></param>
        /// <returns></returns>
        public static FileInfo DownloadFile(string url, string filename, int timeout = 2000, bool skipDownloadIfExists = true)
        {
            if (!File.Exists(filename) || !skipDownloadIfExists)
            {
                FileHelper.EnsureDirectory(filename);
                using (var webClient = new WebClient2(timeout))
                {
                    try
                    {
                        webClient.DownloadFile(url, filename);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return new FileInfo(filename);
        }
    }
}
